package com.example.Cookiedemo;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

@WebServlet("/Cookiedemo_test")
public class Cookiedemo_test extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
//        1.获取cookie
        Cookie[] cookies = request.getCookies();
        boolean flag = false;
        if(cookies != null&&cookies.length > 0){
//            2.遍历cookie
            for (Cookie a:
                    cookies) {
//                3.获取cookie名字
                String name = a.getName();
//                4.判断名称是否是lastTime
                if(name.equals("lastTime")){
                    flag = true;
//                    有该cookie，不是第一次访问
                    String value = a.getValue();
//                    URL解码
                    value = URLDecoder.decode(value,"utf-8");
                    System.out.println(value);
                    response.addCookie(a);
                    response.getWriter().write("<h1>欢迎回来！您上次的访问时间为"+value+"<h1>");

//                    设置cookie的value
//                    获取当前的字符串重新发送时间
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd年 HH:mm:ss");
                    String str_date = sdf.format(date);
//                    URL编码
                    str_date = URLEncoder.encode(str_date,"utf-8");

                    System.out.println(str_date);
                    a.setValue(str_date);
                    a.setMaxAge(60*60*24*30);
                    response.addCookie(a);
                    break;
                }
            }
        }
        if(cookies == null||cookies.length == 0||flag == false){


            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd年 HH:mm:ss");
            String str_date = sdf.format(date);
            str_date = URLEncoder.encode(str_date,"utf-8");
            Cookie cookie = new Cookie("lastTime",str_date);
            cookie.setValue(str_date);
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);
            response.getWriter().write("<h1>您是首次访问该网页，欢迎！<h1>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
